package com.softWang.common.handler;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.softWang.common.aop.annotation.DesensitizeRegex;

import java.io.IOException;

/**
 * 脱敏序列化器
 *
 * 实现 JSON 返回数据时，使用 {@link DesensitizeRegex} 脱敏注解的字段，进行脱敏处理。
 */
public class DesensitizeRegexSerializer extends StdSerializer<String> implements ContextualSerializer {

    private DesensitizeRegex annotation;
    protected DesensitizeRegexSerializer() {
        super(String.class);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) {
        this.annotation = beanProperty.getAnnotation(DesensitizeRegex.class);
        return this;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        if (value == null || value.isEmpty()) {
            gen.writeNull();
            return;
        }
        if(this.annotation != null){
            // 2. 执行脱敏
            String regex = this.annotation.regex();
            String replacer = this.annotation.replacer();
            value = value.replaceAll(regex, replacer);
        }
        gen.writeString(value);
    }

}